package cn.cdutetc.library.service;

import cn.cdutetc.library.entity.pojo.BackupRecord;
import cn.cdutetc.library.entity.pojo.SystemLog;
import cn.cdutetc.library.entity.pojo.User;
import cn.cdutetc.library.mapper.BackupRecordMapper;
import cn.cdutetc.library.mapper.SystemLogMapper;
import cn.cdutetc.library.common.BackupUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 备份服务类
 */
@Slf4j
@Service
public class BackupService {

    @Autowired
    private BackupRecordMapper backupRecordMapper;


    @Autowired
    private SystemLogMapper systemLogMapper;

    @Autowired
    private BackupUtils backupUtils;

    /**
     * 创建备份
     */
    @Transactional
    public BackupRecord createBackup(String backupName, String description, User currentUser) {
        try {
            // 生成备份编码
            String backupCode = "BK" + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            
            // 执行备份
            String backupPath = backupUtils.backupDatabase(backupName, description);
            
            // 获取文件大小
            long fileSize = backupUtils.getFileSize(backupPath);
            
            // 创建备份记录
            BackupRecord backupRecord = new BackupRecord();
            backupRecord.setBackupName(backupName);
            backupRecord.setBackupCode(backupCode);
            backupRecord.setBackupPath(backupPath);
            backupRecord.setBackupSize(fileSize);
            backupRecord.setBackupStatus("success");
            backupRecord.setBackupTime(LocalDateTime.now());
            backupRecord.setDescription(description);
            backupRecord.setCreatedBy(currentUser.getUserId());
            backupRecord.setCreatedByName(currentUser.getRealName());
            
            backupRecordMapper.insert(backupRecord);
            
            // 记录操作日志
            logOperation(currentUser, "创建备份", "备份名称: " + backupName);
            
            return backupRecord;
        } catch (Exception e) {
            log.error("创建备份失败", e);
            
            // 记录失败日志
            BackupRecord failedRecord = new BackupRecord();
            failedRecord.setBackupName(backupName);
            failedRecord.setBackupCode("BK" + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            failedRecord.setBackupPath(""); // 失败时没有备份文件路径
            failedRecord.setBackupSize(0L); // 失败时文件大小为0
            failedRecord.setBackupStatus("failed");
            failedRecord.setBackupTime(LocalDateTime.now());
            failedRecord.setDescription(description);
            failedRecord.setCreatedBy(currentUser.getUserId());
            failedRecord.setCreatedByName(currentUser.getRealName());
            
            backupRecordMapper.insert(failedRecord);
            
            throw new RuntimeException("创建备份失败: " + e.getMessage());
        }
    }


    /**
     * 删除备份
     */
    @Transactional
    public boolean deleteBackup(Integer backupId, User currentUser) {
        try {
            BackupRecord backupRecord = backupRecordMapper.selectById(backupId);
            if (backupRecord == null) {
                throw new RuntimeException("备份记录不存在");
            }
            
            // 删除备份文件
            boolean fileDeleted = backupUtils.deleteBackupFile(backupRecord.getBackupPath());
            
            // 删除数据库记录
            backupRecordMapper.deleteById(backupId);
            
            // 记录操作日志
            logOperation(currentUser, "删除备份", "备份名称: " + backupRecord.getBackupName());
            
            return fileDeleted;
        } catch (Exception e) {
            log.error("删除备份失败", e);
            throw new RuntimeException("删除备份失败: " + e.getMessage());
        }
    }

    /**
     * 获取备份列表
     */
    public Page<BackupRecord> getBackupList(int page, int size) {
        Page<BackupRecord> pageInfo = new Page<>(page, size);
        QueryWrapper<BackupRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("backup_time");
        
        return backupRecordMapper.selectPage(pageInfo, queryWrapper);
    }

    /**
     * 获取备份详情
     */
    public BackupRecord getBackupById(Integer backupId) {
        return backupRecordMapper.selectById(backupId);
    }

    /**
     * 获取系统日志列表
     */
    public Page<SystemLog> getSystemLogList(int page, int size) {
        Page<SystemLog> pageInfo = new Page<>(page, size);
        QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("operation_time");
        
        return systemLogMapper.selectPage(pageInfo, queryWrapper);
    }


    /**
     * 记录操作日志
     */
    private void logOperation(User user, String operation, String remark) {
        try {
            SystemLog systemLog = new SystemLog();
            systemLog.setLogCode("LOG" + System.currentTimeMillis());
            systemLog.setUserId(user.getUserId());
            systemLog.setUserName(user.getRealName());
            systemLog.setOperation(operation);
            systemLog.setOperationTime(LocalDateTime.now());
            systemLog.setIpAddress("127.0.0.1"); // 可以从请求中获取
            systemLog.setLogLevel("INFO");
            systemLog.setModule("BACKUP");
            systemLog.setRemark(remark);
            
            systemLogMapper.insert(systemLog);
        } catch (Exception e) {
            log.error("记录操作日志失败", e);
        }
    }

    /**
     * 保存系统日志
     */
    public void saveSystemLog(SystemLog systemLog) {
        try {
            systemLogMapper.insert(systemLog);
        } catch (Exception e) {
            log.error("保存系统日志失败", e);
            throw new RuntimeException("保存系统日志失败: " + e.getMessage());
        }
    }

}
